#!/usr/bin/env python
#
# http://banssh.googlecode.com/svn/trunk/python/
#
# This is a heartbeat test
#  
#  
import os,sys,re,datetime,pexpect,time
# Note time for sleep

LOG="/var/log/banssh/attacks"
# This is the HeartBeat Log
LOGHB="/var/log/banssh/attacksHB"
HBLOGIN="bansshHB"
SERVER="big"

def login(n):
    p=pexpect.spawn('ssh '+str(HBLOGIN)+'@'+str(n))
    p.expect('.ssword:*')
    time=datetime.datetime.now().strftime("%Y.%m.%d \(%A\) %H:%M:*")
    p.sendline('fakepassword')
    p.expect('.ssword:*')
    p.sendline('fakepassword')
    p.expect('.ssword:*')
    p.terminate()
    return time



def searchlog(n):
    f=open(LOGHB,'r')
    d=f.readlines()
    f.close()
    d.reverse()
    p=re.compile(str(n))
    for i in d[0:40]:
        m=p.search(i)
        if m:
          return True
    return False

def log(n):
    f=open('LoginTest','a')
    f.write(datetime.datetime.now().strftime("%Y.%m.%d (%A) %H:%M:%S")+": ")
    f.write(str(n))
    f.write('\n')
    f.close()


    
def looptest(sleep,loops):
    for i in range(0,loops):
         time.sleep(sleep)
         if searchlog(login(SERVER)):
             log('No worries')
         else:
             log('Hmm ... strange.')


if __name__ == "__main__":
    if searchlog(login(SERVER)):
        print "Ok. All is Good"
    else:
        print "Hmmm... maybe try again?"
    if len(sys.argv) == 3:
        sleep= int(sys.argv[1])
        loops= int(sys.argv[2])
        looptest(sleep,loops)
        log("\n*************  We're done. Going Home ***************")
